﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml;
using System.Xml.Linq;
using CallCenter.Model;
using CallCenter.Properties;

namespace CallCenter.Gui
{
    public partial class OrderCardForm : Form
    {
        private int customerId;
        private Customer customer;
        private Order order;
        private List<Item> items;
        private List<OrderLine> orderLines;

        public OrderCardForm(int customerId)
        {
            this.customerId = customerId;
            InitializeComponent();
        }

        private void OrderCardForm_Load(object sender, EventArgs e)
        {
            order = new Order();
            order.Oprettet = DateTime.Now;
            orderLines = new List<OrderLine>();

            using (var context = new WGRUSEntities())
            {
                items = context.Items.ToList();
                customer = context.Customers.FirstOrDefault(c => c.TelefonNr == customerId);
                //orderLines = context.OrderLines.Where(ol => ol.OrdreNr == order.OrdreNr).ToList();
            }

            if (customer == null)
            {
                MessageBox.Show("Kunde id ukendt", "Fejl", MessageBoxButtons.OK, MessageBoxIcon.Error);
                this.Close();
                return;
            }

            itemBindingSource.CurrentChanged += itemBindingSource_CurrentChanged;
            itemBindingSource.DataSource = items;
            orderLineBindingSource.DataSource = orderLines;

            FillGui();
        }

        private void bt_AddOrderLine_Click(object sender, EventArgs e)
        {
            double amount;
            if (!double.TryParse(txt_Amount.Text, out amount))
            {
                MessageBox.Show("Indtast antal", "Fejl", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            if (string.IsNullOrEmpty(txt_VareId.Text.Trim()))
            {
                MessageBox.Show("Vælg/indtast vare id", "Fejl", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            using (var context = new WGRUSEntities())
            {
                Item item = context.Items.FirstOrDefault(i => i.VareId == txt_VareId.Text.Trim());
                if (item == null)
                {
                    MessageBox.Show("Vare id ukendt", "Fejl", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                OrderLine orderLine = new OrderLine
                {
                    Antal = amount,
                    Enhedspris = item.Enhedspris,
                    VareBeskrivelse = item.Beskrivelse,
                    VareId = item.VareId
                };
                orderLines.Add(orderLine);
                orderLineBindingSource.ResetBindings(true);
            }
        }

        private void bt_ResetOrderLine_Click(object sender, EventArgs e)
        {
            orderLines.Clear();
        }

        private void bt_Cancel_Click(object sender, EventArgs e)
        {
            orderLines.Clear();
            this.Close();
        }

        private void bt_CreateOrder_Click(object sender, EventArgs e)
        {
            if (!FillOrder(order))
                return;

            using (var context = new WGRUSEntities())
            {
                context.Customers.Attach(customer);
                customer.Orders.Add(order);
                foreach (var orderLine in orderLines)
                {
                    order.OrderLines.Add(orderLine);
                }

                context.SaveChanges();
                exportOrder(order);
            }


            MessageBox.Show("Ordre oprettet", "Info", MessageBoxButtons.OK, MessageBoxIcon.Information);
            this.Close();
        }


        private void FillGui()
        {
            kundeNrTextBox.Text = customer.TelefonNr.ToString();
            leveringAttTextBox.Text = "";
            leveringNavnTextBox.Text = customer.Navn;
            leveringGadeTextBox.Text = customer.Gade;
            leveringPostNrTextBox.Text = customer.PostNr.ToString();
            leveringByTextBox.Text = customer.By;
        }

        private bool FillOrder(Order order)
        {
            int zipCode;
            if (!int.TryParse(leveringPostNrTextBox.Text, out zipCode))
            {
                MessageBox.Show("Postnummer skal være numerisk", "Fejl", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }

            order.LeveringAtt = leveringAttTextBox.Text;
            order.LeveringNavn = leveringNavnTextBox.Text;
            order.LeveringGade = leveringGadeTextBox.Text;
            order.LeveringPostNr = zipCode;
            order.LeveringBy = leveringByTextBox.Text;

            return true;
        }


        private void itemBindingSource_CurrentChanged(object sender, EventArgs e)
        {
            Item item = itemBindingSource.Current as Item;
            if (item == null)
                return;

            txt_VareId.Text = item.VareId;
        }

        private void exportOrder(Order order)
        {
            var cust = order.Customer;
            var xmlOrder =
                new XDocument(
                    new XElement("Order",
                        new XElement("Customer",
                            new XElement("KundeId", cust.TelefonNr),
                            new XElement("Navn", cust.Navn),
                            new XElement("Gade", cust.Gade),
                            new XElement("PostNr", cust.PostNr),
                            new XElement("By", cust.By
                                )),
                        new XElement("OrderDetails",
                            new XElement("LeveringAtt", order.LeveringAtt),
                            new XElement("LeveringNavn", order.LeveringNavn),
                            new XElement("LeveringGade", order.LeveringGade),
                            new XElement("LeveringPostNr", order.LeveringPostNr),
                            new XElement("LeveringBy", order.LeveringBy),
                            new XElement("OrdreReference", order.OrdreReference),
                            new XElement("OrderLines",
                                from ol in order.OrderLines
                                select new XElement("OrderLine",
                                    new XElement("VareId", ol.VareId),
                                    new XElement("VareBeskrivelse", ol.VareBeskrivelse),
                                    new XElement("Enhedspris", ol.Enhedspris),
                                    new XElement("Antal", ol.Antal)
                                    )
                                )
                            )
                        ));

            if (!Directory.Exists(Settings.Default.OrderPath))
            {
                Directory.CreateDirectory(Settings.Default.OrderPath);
            }

            string filename = Settings.Default.OrderPath + string.Format("\\Order-{0:yyyy-MM-dd}T{0:HH-mm-ss-ffff}.xml", order.Oprettet);

            FileStream writer = File.Create( filename);
            XmlWriter xmlWriter = new XmlTextWriter(writer, Encoding.UTF8);
            xmlOrder.WriteTo(xmlWriter);
            xmlWriter.Close();
            writer.Close();
        }
    }
}